﻿
using WebCarERP.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Web.Mvc;
using WebCarERP.Models;

namespace WebCarERP.Controllers
{
    public class BaseController : Controller
    {
        protected static WebCarERPEntities db = new WebCarERPEntities();

        //  IBLL.IActionInfoService _actioninfoService = new ActionInfoService();
        // IBLL.IUserInfoService _userInfoService = new UserInfoService();
        // 定义一个基类的RoleUserModel对象
        public RoleUserModel CurrentUserInfo { get; set; }

        // <summary>
        // 重写基类在Action之前执行的方法
        //</summary>
        // <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            #region -----校验用户是否登录进入网站的-----

            base.OnActionExecuting(filterContext);
            CurrentUserInfo = Session["RoleUserModel"] as RoleUserModel;

            //检验用户是否已经登录，如果登录则不执行，否则则执行下面的跳转代码
            if (CurrentUserInfo == null)
            {
                //HttpContext.Cache.Insert("errorMessage", "您好！您的登录状态已经失效请重新登录！");

                string message = "&errorMessage=" + Server.UrlEncode("您好！您的登录状态已经失效请重新登录！");
                if (HttpContext.Request.Url.ToString().IndexOf("/Home") > 0 || HttpContext.Request.Url.IsAbsoluteUri)
                {
                    message = "";
                }
                Response.Redirect("/Login/Index?returnUrl=" + Server.UrlEncode(Request.Url.ToString()) + message);
            }
            //else
            //{
            //    Object key = HttpContext.Cache[CurrentUserInfo.userid.ToString()];
            //    string sessionid = key.ToString();
            //    if (!string.IsNullOrEmpty(sessionid))
            //    {
            //        if (sessionid != HttpContext.Session.SessionID)
            //        {
            //            //HttpContext.Cache.Insert("errorMessage", "您好！您的账号已经在其他地方登陆！");
            //            CurrentUserInfo = null;
            //            Session.Clear();
            //            Session.Abandon();
            //            Response.Redirect("/Login/Index?returnUrl=" + Server.UrlEncode(Request.Url.ToString()) + "&errorMessage=" + Server.UrlEncode("您好！您的账号已经在其他地方登陆！"));
            //        }
            //    }
            //}

            #endregion -----校验用户是否登录进入网站的-----

            #region ------//留个接口------

            //if (CurrentUserInfo.UName == "admin")
            //{
            //    return;
            //}

            #endregion ------//留个接口------

            #region -------检验用户是否有访问此地址的权利----

            ////先将当前的请求，到权限表里面去找对应的数据
            ////拿到当前请求的URL地址
            //string requestUrl = filterContext.HttpContext.Request.Path;
            ////拿到当前请求的类型
            //string requestType = filterContext.HttpContext.Request.RequestType.ToLower().Equals("get") ? "HttpGet" : "HttpPost";
            ////然后和权限表进行对比，如果取出来则通过请求，否则不通过
            ////取出当前权限的数据
            //var currentAction = _actioninfoService.LoadEntities(c => c.RequestUrl.Equals(requestUrl, StringComparison.InvariantCultureIgnoreCase) && c.RequestHttpType.Equals(requestType)).FirstOrDefault();
            ////如果没有权限对应当前请求的话，直接干掉
            //if (currentAction == null)
            //{
            //    EndRequest();
            //}
            ////想去用户权限表里面查询有没有数据
            ////分析第一条线路 RoleUserModel->R_UserInfo_ActionInfo->ActionInfo
            ////拿到当前的用户信息
            //var userCurrent = _userInfoService.LoadEntities(u => u.ID == CurrentUserInfo.ID).FirstOrDefault();
            //var temp = (from r in userCurrent.R_UserInfo_ActionInfo
            //            where r.ActionInfoID == currentAction.ID
            //            select r).FirstOrDefault();
            //if (temp != null)
            //{
            //    if (temp.HasPermation)
            //    {
            //        return;
            //    }
            //    else
            //    {
            //        EndRequest();
            //    }
            //}

            ////分析第二条线路 RoleUserModel->ActionGroup->ActionInfo
            //var groups = from n in userCurrent.ActionGroup //拿到当前用户所有的组
            //             select n;
            ////根据组信息遍历出权限信息
            //bool isPass = (from g in groups
            //               from a in g.ActionInfo
            //               select a.ID).Contains(currentAction.ID);
            //if (isPass)   //11，23，34不包含4
            //{
            //    return;
            //}

            ////分析第三条线路 分为两个
            ////1)RoleUserModel->R_UserInfo_Role->Role->ActionInfo

            ////先拿到用户对应的所有的角色
            //var UserRoles = from r in userCurrent.R_UserInfo_Role
            //                select r.Role;
            ////拿到角色对应的所有权限
            //var Rolesaction = (from r in UserRoles
            //                   from a in r.ActionInfo
            //                   select a.ID);
            //if (Rolesaction.Contains(currentAction.ID))
            //{
            //    return;
            //}

            ////2)RoleUserModel->R_UserInfo_Role->Role->ActionGroup->ActionInfo
            ////拿到组信息
            //var RoleGroupActions = from r in UserRoles
            //                       from g in r.ActionGroup
            //                       select g;
            ////拿到所有的组信息
            //var groupActions = from r in RoleGroupActions
            //                   from g in r.ActionInfo
            //                   select g.ID;
            //if (groupActions.Contains(currentAction.ID))
            //{
            //    return;
            //}

            #endregion -------检验用户是否有访问此地址的权利----

            return;
        }

        [OutputCache(CacheProfile = "TestConfigCache")]
        public ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

 

        //获得页数下拉框
        [OutputCache(CacheProfile = "TestConfigCache")]
        public IEnumerable<SelectListItem> GetDropPage(int max)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            for (int i = 1; i <= max; i++)
            {
                items.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
            }
            return items;
        }

        public void EndRequest()
        {
            Response.Redirect("/Error.html");
        }

        //循环去除datatable中的空行
        public static System.Data.DataTable removeEmpty(System.Data.DataTable dt)
        {
            List<DataRow> removelist = new List<DataRow>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                bool rowdataisnull = true;
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
                    {
                        rowdataisnull = false;
                    }
                }
                if (rowdataisnull)
                {
                    removelist.Add(dt.Rows[i]);
                }
            }
            for (int i = 0; i < removelist.Count; i++)
            {
                dt.Rows.Remove(removelist[i]);
            }
            return dt;
        }

        /// <summary>
        /// 获取数据集
        /// </summary>
        /// <param name="strcon">获取excel版本连接字符串</param>
        /// <param name="ds">sheet1的数据集</param>
        public static void ImportExcelDataSet(string strcon, out DataSet ds)
        {
            OleDbConnection odcon = new OleDbConnection(strcon);//建立连接
            odcon.Open();//打开连接
            //把数据集dataset放到控件中显示
            //OleDbDataAdapter odda = new OleDbDataAdapter("select * from " + Tablename, odcon);
            System.Data.DataTable TableWorkNames = odcon.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
            OleDbConnection con = new OleDbConnection(strcon);
            OleDbDataAdapter odda = new OleDbDataAdapter("select  * from [sheet1$]  ", con);//" + TableWorkNames.Rows[0]["Table_Name"] + "

            ds = new DataSet();
            try
            {
                odda.Fill(ds);
                odda.Dispose();
                odcon.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        /// <summary>
        /// 使用新的API，批量导入,这个速度很快,很显然，这种方式只写一次日志，不会为每一行写日志
        /// </summary>
        /// <param name="SqlConn">数据库连接配置</param>
        /// <param name="dataTableName">数据库表名</param>
        /// <param name="dt">源数据</param>
        /// <param name="columnName">源数据字段对应目标数据库字段</param>
        /// <param name="BatchSize">每一次批次提交服务器的行数</param>
        protected void InsetData(string SqlConn, string dataTableName, DataTable dt, string[] columnName, int BatchSize)
        {
            using (SqlConnection conn = new SqlConnection(SqlConn))
            {
                SqlBulkCopy bcp = new SqlBulkCopy(conn);
                bcp.DestinationTableName = dataTableName;
                bcp.BatchSize = BatchSize;//这是批尺寸可以调整
                for (int i = 0; i < columnName.Length; i++)
                {
                    bcp.ColumnMappings.Add(columnName[i], columnName[i]);
                }
                conn.Open();
                bcp.WriteToServer(dt);
            }
        }

 
        public delegate bool EqualsComparer<T>(T x, T y);

        public class Compare<T> : IEqualityComparer<T>
        {
            private EqualsComparer<T> _equalsComparer;

            public Compare(EqualsComparer<T> equalsComparer)
            {
                this._equalsComparer = equalsComparer;
            }

            public bool Equals(T x, T y)
            {
                if (null != this._equalsComparer)
                    return this._equalsComparer(x, y);
                else
                    return false;
            }

            public int GetHashCode(T obj)
            {
                return obj.ToString().GetHashCode();
            }
        }

    }
}